import subprocess
import requests
import time
import os
import json
from datetime import date, timedelta, datetime
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from openpyxl import load_workbook
from openpyxl import Workbook
import hashlib


def get_post_data(gh_id, password):
    h = hashlib.md5()
    h.update(password.encode(encoding='utf-8'))
    pwd = h.hexdigest()

    data = {
        'username': gh_id,
        'pwd': pwd,
        'imgcode': '',
        'f': 'json',
        'userlang': 'zh_CN',
        'token': '',
        'lang': 'zh_CN',
        'ajax': '1'
    }

    return data


log_filename = '错误报告{}.log'.format(time.strftime('%Y-%m-%d %H%M%S'))
debug_log = 'debug{}.log'.format(time.strftime('%Y-%m-%d %H%M%S'))
date_format = '%Y-%m-%d'


def log_error(line, logtype):
    if logtype == 'log':
        with open(log_filename, 'a', encoding='utf-8') as f:
            f.write(line + "\n")
    elif logtype == 'debug':
        with open(debug_log, 'a', encoding='utf-8') as f:
            f.write(line + "\r\n")


def get_date_from_timestamp(timestamp):
    return time.strftime(date_format, time.localtime(timestamp))


def get_datetime_from_timestamp(timestamp):
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))


# 计算两个日期相差的天数
def get_day_interval(sdate, edate):
    sdate = time.strptime(sdate, "%Y-%m-%d")
    edate = time.strptime(edate, "%Y-%m-%d")
    sdate = datetime(sdate[0], sdate[1], sdate[2])
    edate = datetime(edate[0], edate[1], edate[2])
    return (edate - sdate).days + 1


# 获取两个日期之间的所有天数列表并格式化
def get_day_interval_format(sdate, edate):
    if sdate == edate:
        return [sdate]
    else:
        data = []
        day = timedelta(days=1)
        count = get_day_interval(sdate, edate)
        sdate = datetime.strptime(sdate, "%Y-%m-%d")
        edate = datetime.strptime(edate, "%Y-%m-%d")
        for i in range(count):
            data.append((sdate + day*i).strftime(date_format))
        return data


def set_cookies(session, cookie_dict):
    for name, value in cookie_dict.items():
        session.cookies.set(name, value)


def requests_retry_session(
    retries=3,
    backoff_factor=0.3,
    status_forcelist=(500, 502, 504),
    session=None,
):
    session = session or requests.Session()
    retry = Retry(
        total=retries,
        read=retries,
        connect=retries,
        backoff_factor=backoff_factor,
        status_forcelist=status_forcelist,
    )
    adapter = HTTPAdapter(max_retries=retry)
    session.mount('http://', adapter)
    session.mount('https://', adapter)
    return session


def show_image(filename):
    subprocess.call([filename], shell=True)


def get_today():
    return date.today().strftime(date_format)


def get_day_before_today(diff, today=get_today()):
    if diff == 0:
        return today
    return (datetime.strptime(today, date_format) - timedelta(diff)).strftime(date_format)


def get_yesterday():
    return get_day_before_today(1)


def get_data_file_path(gh_id, data_file, data_date=get_today()):
    return 'data/{}/{}/{}'.format(gh_id, data_date, data_file)


def has_data_file(gh_id, data_file, data_date=get_today()):
    return os.path.isfile(get_data_file_path(gh_id, data_file, data_date))


def open_write_data_file(gh_id, data_file, data_date=get_today()):
    filename = get_data_file_path(gh_id, data_file, data_date)
    os.makedirs(os.path.dirname(filename), exist_ok=True)
    return open(filename, 'w')


def get_json_file(gh_id, data_date, data_file, data_type=dict):
    try:
        return json.load(open(get_data_file_path(gh_id, data_file, data_date), 'r'))
    except OSError:
        return data_type()


def make_workbook(sheet_name=None):
    workbook = Workbook()
    sheet = workbook.active
    if sheet_name:
        sheet.title = sheet_name
    return workbook, sheet


class AccountLibrary:

    def __init__(self, accounts_list_filename):
        self.accounts = {}
        self.account_gh_list = []
        try:
            self.workbook = load_workbook(accounts_list_filename)
            self.sheet = self.workbook.active
            self.columns = ['charge', 'nickname', 'wx_id',
                            'gh_id', 'pwd', 'fans_src', 'type', 'gender']
            for row_index in range(2, self.sheet.max_row + 1):
                account = {}
                for index, column in enumerate(self.columns):
                    account[column] = self.sheet.cell(
                        row=row_index, column=index + 1).value
                if not account['gh_id']:
                    continue
                account['gh_id'] = account['gh_id'].strip()
                self.accounts[account['gh_id']] = account
                self.account_gh_list.append(account['gh_id'])
        except FileNotFoundError:
            print('账号列表不存在，请建立文件“{}”'.format(accounts_list_filename))

    def get_account_list(self):
        # prevent modify
        return self.account_gh_list[:]

    def get_account_chunks(self, size):
        the_list = self.get_account_list()
        return [the_list[i * size:(i + 1) * size] for i in range((len(the_list) + size - 1) // size)]

    def get_account_data(self, gh_id):
        return self.accounts[gh_id] if gh_id in self.accounts else None


def default_library():
    return AccountLibrary('账号列表.xlsx')
